package com.example.bookshop.controller;

import com.example.bookshop.bean.BookBean;
import com.example.bookshop.bean.BookTypeBean;
import com.example.bookshop.bean.PageBean;
import com.example.bookshop.bean.ResultBean;
import com.example.bookshop.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class BookController {
    @Autowired
    private BookDao bookDao;

    @RequestMapping("/add_book")
    public ResultBean addBook(BookBean book){
        ResultBean result = new ResultBean();
        if (bookDao.insertBook(book)==1) {
            //添加语句成功
            result.setCode(1);
            result.setMsg("添加成功!");
        }else {
            result.setCode(-1);
            result.setMsg("添加失败!");
        }
        return result;
    }

    /**
     * 查找所有书信息
     *
     * @return {@link ResultBean}
     */
    @RequestMapping("/find_books_page")
    public ResultBean findBook (Integer pageNow){
        ResultBean result = new ResultBean();
        PageBean page = new PageBean();
        page.setRowCount(bookDao.getRowCount());//总行数
        page.setPageCount(page.getRowCount()%page.getPageSize()==0
                ? page.getRowCount()/page.getPageSize()
                : page.getRowCount()/page.getPageSize()+1);//总页数
        page.setPageNow(pageNow==null?1:
                        pageNow<1?1:
                        pageNow>page.getPageCount()?page.getPageCount():pageNow);
        List<BookBean> books = bookDao.selectBookPage(page);
        Map<String,Object> map = new HashMap<>();
        map.put("page",page);
        map.put("books",books);
        result.setCode(1);
        result.setData(map);
        return result;
    }

    /**
     * 删除书
     *
     * @param bookId 书id
     * @return {@link ResultBean}
     */
    @RequestMapping("/drop_book")
    public ResultBean dropBook(Integer bookId){
        ResultBean result = new ResultBean();
        if (bookDao.deleteBook(bookId)==1){
            result.setCode(1);
            result.setMsg("删除成功!");
        }else{
            result.setCode(-1);
            result.setMsg("删除失败!");
        }
        return  result;
    }

    @RequestMapping("/edit_book")
    public ResultBean editBook(BookBean book){
        ResultBean result = new ResultBean();
        if (bookDao.updateBook(book)==1){
            result.setCode(1);
            result.setMsg("修改成功!");
        }else {
            result.setCode(1);
            result.setMsg("修改失败!");
        }
        return result;
    }
}
